# -*- coding: utf-8 -*-
# @Time    : 2024/9/27 14:18
# @Author  : Alvin
# @File    : SyncOrderLanShouTask.py
# @Des     : 同步单揽收

import logging
import logging.handlers
import multiprocessing
import os
import time
from functools import partial
from typing import List, Dict

from handler.SyncOrderLanShouImpl import SyncOrderLanShouImpl
from utils import CommonUtil
from utils.DatabaseHandler import DatabaseHandler


class SyncOrderLanShouTask:

    def __init__(self):
        self.log_text = "同步单揽收任务"
        self.chunk_size = 1000
        self.max_workers = 6
        self.init_logging()

    def init_logging(self):
        """
        日志文件设置
        """
        if not os.path.exists("log"):
            os.makedirs("log")
        logger = logging.getLogger()
        logger.setLevel(20)

        sh = logging.StreamHandler()
        current_path = os.path.dirname(__file__)
        log_file = f"{current_path}/log/lanshou_task.log"
        file_log = logging.handlers.TimedRotatingFileHandler(log_file, 'MIDNIGHT', 1, 15)
        formatter = logging.Formatter('[%(asctime)s] [%(levelname)-7s] [%(module)s:%(filename)s-%(funcName)s-%(lineno)d] %(message)s')
        sh.setFormatter(formatter)
        file_log.setFormatter(formatter)

        logger.addHandler(sh)
        logger.addHandler(file_log)

        logging.info("Current log level is : %s", logging.getLevelName(logger.getEffectiveLevel()))

    """
    步骤：
        1、获取数据库中所有需要揽收的数据
        2、检查登录状态
        3、开始揽收
        
        将所有数据都查出来，以chunk_size 分块，然后传入实现类中使用多线程更新
    """

    def excute_sync_order_lan_shou(self):
        logging.info(f"----------------------{self.log_text}揽收任务 start -----------------------")
        dbDataList = DatabaseHandler().get_sync_order_lanshou_list()
        if dbDataList is None or len(dbDataList) <= 0:
            logging.info(f"{self.log_text}揽收任务数量为0，任务结束")
            return

        all_data_list = CommonUtil.splitList(dbDataList, self.chunk_size)
        logging.info(f"{self.log_text}数据库查询结束,共获取 {len(dbDataList)} 条数据，划分为 {len(all_data_list)} 个分块")

        for index, data_list in enumerate(all_data_list):
            batch_index = index + 1
            logging.info(f"开始第：{batch_index}/{len(all_data_list)}次揽收")
            syncOrderLanShouImpl = SyncOrderLanShouImpl()
            syncOrderLanShouImpl.start_handle_dy_lanshou_task(batch_index, data_list)
        logging.info(f"{self.log_text}揽收任务结束时间:%s", time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
        logging.info(f"----------------------------------------{self.log_text}揽收任务 all end---------------------------------------")


if __name__ == '__main__':
    syncOrderLanShouTask = SyncOrderLanShouTask()
    syncOrderLanShouTask.excute_sync_order_lan_shou()
